import { createContext, useRef, useState, useContext, useEffect } from "react";
import { PageContainer, View, Text } from "@tarojs/components";
import ScrollPicker from "@/components/ScrollPicker";
import NumberEditor from "@/components/NumberEditor";
import { TValue, ScrollPickerProps, NumberEditorProps } from "@/types";
import Taro from "@tarojs/taro";

// 初始状态
const initialState = {
  type: "",
  show: false,
  showConfirm: true,
  getNode: (props: {}) => null,
  round: true,
  props: {},
  onConfirm: (_v?: TValue) => {},
  onClose: () => {},
};

// 创建 Context
export const PopupContext = createContext<{
  state: typeof initialState;
  openPopup: (config: Config) => void;
  closePopup: () => void;
}>({
  state: initialState,
  openPopup: () => {},
  closePopup: () => {},
});

type Config = {
  type?: string;
  show?: boolean;
  showConfirm?: boolean;
  getNode?: (props?: any) => any;
  round?: boolean;
  props?: ScrollPickerProps | NumberEditorProps;
  onConfirm?: (v?: TValue) => void;
  onClose?: () => void;
};

// 创建 Provider
export const PopupProvider = ({ children }) => {
  const [state, setState] = useState(initialState);
  const scrollRef = useRef<{ getValue: () => any }>(null);

  const openPopup = (config: Config) => {
    setState({
      ...initialState,
      ...config,
      show: true,
    });
  };

  const closePopup = () => {
    setState({
      ...state,
      getNode: () => null,
      show: false,
      type: "",
    });
    state.onClose?.();
  };

  const handleConfirm = () => {
    if (state.type === "picker" && scrollRef.current) {
      state.onConfirm(scrollRef.current.getValue());
    } else {
      state.onConfirm();
    }
    closePopup();
  };

  return (
    <PopupContext.Provider value={{ state, openPopup, closePopup }}>
      {children}
      <PageContainer
        show={state.show}
        round={state.round}
        onLeave={closePopup}
        onClickOverlay={closePopup}
      >
        {state.showConfirm && (
          <View className="global-picker-header">
            <Text className="cancel" onClick={closePopup}>
              取消
            </Text>
            <Text className="confirm" onClick={handleConfirm}>
              确定
            </Text>
          </View>
        )}
        {state.type === "picker" && (
          <ScrollPicker
            {...(state.props as ScrollPickerProps)}
            ref={scrollRef}
          />
        )}

        {state.type === "number" && (
          <NumberEditor
            {...(state.props as NumberEditorProps)}
            onConfirm={(v) => {
              state.onConfirm(v);
              closePopup();
            }}
          />
        )}

        {state.getNode?.(state?.props)}
      </PageContainer>
    </PopupContext.Provider>
  );
};

export const usePopup = () => useContext(PopupContext);
